<?php

namespace App\Http\Controllers\Single;

use App\Http\Controllers\Controller;
use App\Http\Requests\PostQueryRequest;
use App\Http\Resources\PostCollection;
use App\Http\Resources\PostResource;
use App\Services\WPQueryService;
use App\Utils\ApiResponse;
use Illuminate\Http\Request;

class Get extends Controller
{

    /**
     * @group WordPress文章
     * @subgroup 单篇文章
     *
     * 根据文章ID获取单篇文章的详细信息。
     *
     * @urlParam id integer required 文章ID Example: 1
     *
     * @response 200 {
     *   "code": 200,
     *   "message": "获取文章成功",
     *   "data": {
     *     "id": 1,
     *     "title": "示例文章标题",
     *     "slug": "sample-post",
     *     "content": "这是文章的完整内容...",
     *     "excerpt": "这是文章摘要...",
     *     "status": "publish",
     *     "type": "post",
     *     "author": {
     *       "id": 1,
     *       "name": "管理员",
     *       "slug": "admin",
     *       "avatar": "https://example.com/avatar.jpg"
     *     },
     *     "cover": "https://example.com/cover.jpg",
     *     "images": ["https://example.com/image1.jpg"],
     *     "categories": [
     *       {
     *         "id": 1,
     *         "name": "技术",
     *         "slug": "tech",
     *         "description": "技术相关文章",
     *         "count": 10
     *       }
     *     ],
     *     "tags": [
     *       {
     *         "id": 1,
     *         "name": "WordPress",
     *         "slug": "wordpress",
     *         "description": "WordPress相关",
     *         "count": 5
     *       }
     *     ],
     *     "date": {
     *       "created": "2024-03-15 10:30:00",
     *       "modified": "2024-03-15 11:00:00"
     *     },
     *     "permalink": "https://example.com/sample-post/",
     *     "comment_count": 3,
     *     "comment_status": "open"
     *   }
     * }
     *
     * @response 404 {
     *   "code": 404,
     *   "message": "文章不存在",
     *   "data": null
     * }
     *
     * @response 500 {
     *   "code": 500,
     *   "message": "获取文章失败: 数据库连接错误",
     *   "data": null
     * }
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function single(Request $request)
    {
        try {
            $id = $request->route('id');

            if (!$id || !is_numeric($id)) {
                return ApiResponse::error('无效的文章ID', 400, 400);
            }

            // 获取文章
            $post = get_post($id);

            if (!$post || $post->post_status !== 'publish') {
                return ApiResponse::error('文章不存在', 404, 404);
            }

            // 使用PostResource格式化数据
            $postResource = new PostResource($post);

            return ApiResponse::success($postResource, '获取文章成功');
        } catch (\Exception $e) {
            return ApiResponse::error('获取文章失败: ' . $e->getMessage(), 500, 500);
        }
    }
    /**
     * @group WordPress文章
     * @subgroup 文章列表
     *
     * 获取WordPress文章列表，支持多种查询条件和分页。
     *
     * @queryParam post_type string 文章类型，默认为post Example: post
     * @queryParam post_status string 文章状态 Example: publish
     * @queryParam limit integer 每页数量，范围1-100，默认10 Example: 10
     * @queryParam page integer 页码，从1开始，默认1 Example: 1
     * @queryParam orderby string 排序字段 Example: date
     * @queryParam order string 排序方式，ASC或DESC，默认DESC Example: DESC
     *
     * @queryParam ids string 包含的文章ID，多个用逗号分隔 Example: 1,2,3
     * @queryParam not_ids string 排除的文章ID，多个用逗号分隔 Example: 4,5,6
     *
     * @queryParam cat integer 分类ID Example: 1
     * @queryParam cat_ids string 包含的分类ID，多个用逗号分隔 Example: 1,2,3
     * @queryParam not_cat_ids string 排除的分类ID，多个用逗号分隔 Example: 4,5,6
     *
     * @queryParam tag integer 标签ID Example: 1
     * @queryParam tag_ids string 包含的标签ID，多个用逗号分隔 Example: 1,2,3
     * @queryParam not_tag_ids string 排除的标签ID，多个用逗号分隔 Example: 4,5,6
     *
     * @queryParam author integer 作者ID Example: 1
     *
     * @queryParam date string 精确日期，格式YYYY-MM-DD Example: 2024-03-15
     * @queryParam date_from string 开始日期，格式YYYY-MM-DD Example: 2024-03-01
     * @queryParam date_to string 结束日期，格式YYYY-MM-DD Example: 2024-03-31
     *
     * @queryParam s string 搜索关键词，最多200字符 Example: WordPress
     *
     * @queryParam ignore_sticky_posts boolean 是否忽略粘性文章，默认false Example: false
     * @queryParam sticky_only string 是否只返回粘性文章，1或0 Example: 0
     *
     * @response 200 {
     *   "code": 200,
     *   "message": "获取文章列表成功",
     *   "data": {
     *     "list": [
     *       {
     *         "id": 1,
     *         "title": "示例文章标题",
     *         "slug": "sample-post",
     *         "excerpt": "这是文章摘要...",
     *         "status": "publish",
     *         "type": "post",
     *         "author": {
     *           "id": 1,
     *           "name": "管理员",
     *           "slug": "admin",
     *           "avatar": "https://example.com/avatar.jpg"
     *         },
     *         "cover": "https://example.com/cover.jpg",
     *         "images": ["https://example.com/image1.jpg"],
     *         "categories": [
     *           {
     *             "id": 1,
     *             "name": "技术",
     *             "slug": "tech",
     *             "description": "技术相关文章",
     *             "count": 10
     *           }
     *         ],
     *         "tags": [
     *           {
     *             "id": 1,
     *             "name": "WordPress",
     *             "slug": "wordpress",
     *             "description": "WordPress相关",
     *             "count": 5
     *           }
     *         ],
     *         "date": {
     *           "created": "2024-03-15 10:30:00",
     *           "modified": "2024-03-15 11:00:00"
     *         },
     *         "permalink": "https://example.com/sample-post/",
     *         "comment_count": 3,
     *         "comment_status": "open",
     *         "row_list_options": {
     *           "list_display_data": "title,excerpt,date",
     *           "image_position": "left",
     *           "image_display": "cover"
     *         }
     *       }
     *     ],
     *     "pagination": {
     *       "current_page": 1,
     *       "limit": 10,
     *       "total": 50,
     *       "total_pages": 5,
     *       "has_next_page": true,
     *       "has_prev_page": false
     *     }
     *   }
     * }
     *
     * @response 422 {
     *   "code": 422,
     *   "message": "请求参数验证失败",
     *   "data": {
     *     "validation_errors": {
     *       "limit": ["每页数量最多为100"]
     *     }
     *   }
     * }
     *
     * @response 500 {
     *   "code": 500,
     *   "message": "查询文章列表失败: 数据库连接错误",
     *   "data": null
     * }
     *
     * @param PostQueryRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(PostQueryRequest $request)
    {
        try {
            // 使用服务类获取查询参数
            $params = WPQueryService::buildQueryParams($request);
            $params = WPQueryService::validateAndCleanParams($params);
            // 创建WP_Query实例
            $wp_query = new \WP_Query($params);
            // 处理查询结果
            $posts = [];
            if ($wp_query->have_posts()) {
                while ($wp_query->have_posts()) {
                    $wp_query->the_post();
                    $posts[] = get_post();
                }
                wp_reset_postdata();
            }
            // 构建分页信息
            $pagination = PostCollection::buildPagination($wp_query, $request);

            // 使用Resource格式化数据并返回
            $postCollection = new PostCollection($posts, $pagination);

            return ApiResponse::success($postCollection->toArray($request), '获取文章列表成功');
        } catch (\Exception $e) {
            return ApiResponse::error('查询文章列表失败: ' . $e->getMessage(), 500, 500);
        }
    }
}
